package com.jbm.core.common.ResponseRecvCallback;

import com.jbm.core.common.AutoCall;
import com.jbm.core.common.ConnectAgent;
import com.jbm.core.common.IoSessionShell;
import com.jbm.core.iface.IAcross;
import com.jbm.core.iface.IP2P;
import com.jbm.core.pb.PBIAcross;
import com.jbm.core.pb.PBIP2P;
import org.apache.mina.core.session.IoSession;

/**
 * Created by root on 17-3-8.
 */
public class IP2P_RRCallback implements ResponseRecvCallback
{
	protected IoSessionShell m_ios;
	protected ConnectAgent m_ca;
	protected boolean m_isclosed;

	protected final Object m_status_mutex = new Object();

	public IP2P_RRCallback()
	{
		m_ios = null;
		m_ca = null;

		m_isclosed = false;
	}


	public IP2P_RRCallback(ConnectAgent ca, IoSessionShell ios)
	{
		this();

		m_ca = ca;
		m_ios = ios;
	}

	public void PushResponse (long start, long cur, PBIAcross.IAcross request, IAcross content, PBIAcross.IAcross response, Object exinfo, boolean isfirst)
	{
		synchronized (m_status_mutex)
		{
			if ( m_isclosed )
				return;

			if (request.getMethod().equals("ConnectP2P"))
			{
				if (response == null)
					return;

				if (response.getCode() != 200)
				{
					m_isclosed = true;

					m_ca.setM_connectisclose(false);

					return;
				}

				Object res = AutoCall.g_autocall.Call(m_ios,
						"IP2P", "ArcossNAT",
						new IP2P(request.getFromid(), request.getToid(), request.getFromtag(),true),
						request.getFromid(), request.getToid(),
						request.getFromtag(), request.getTotag(),
						m_ca.GetQIndex(), true, false, false, false,
						this);

				if ( res != null )
					m_ca.setM_connectisclose(false);
			} else if (request.getMethod().equals("ArcossNAT"))
			{
				if (response == null)
					return;

				m_isclosed = true;

				if (response.getCode() != 200)
				{
					m_ca.setM_connectisclose(false);

					return;
				}

				m_ca.ReConnectP2P(false, ((IP2P)content).m_initiate, m_ios);
			}
		}
	}
}
